<template>
  <div class="consultation-page">
    <div class="page-header">
      <h1 class="page-title">AI智能咨询</h1>
      <p class="page-subtitle">专业解答您的标书相关问题，提供智能建议</p>
    </div>
    
    <div class="page-content">
      <div class="consultation-layout">
        <!-- 左侧咨询历史 -->
        <div class="consultation-sidebar">
          <div class="sidebar-header">
            <h3>咨询历史</h3>
            <el-button type="primary" size="small" class="new-chat-btn">
              <el-icon><Plus /></el-icon>
              新对话
            </el-button>
          </div>
          
          <div class="chat-history">
            <div
              v-for="chat in chatHistory"
              :key="chat.id"
              class="chat-item"
              :class="{ active: activeChatId === chat.id }"
              @click="selectChat(chat.id)"
            >
              <div class="chat-icon">
                <el-icon><ChatDotRound /></el-icon>
              </div>
              <div class="chat-info">
                <div class="chat-title">{{ chat.title }}</div>
                <div class="chat-time">{{ formatTime(chat.lastTime) }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右侧对话区域 -->
        <div class="consultation-main">
          <div class="chat-container">
            <!-- 对话头部 -->
            <div class="chat-header">
              <div class="chat-title">
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ currentChat?.title || '新对话' }}</span>
              </div>
              <div class="chat-actions">
                <el-button type="text" size="small" @click="clearChat">
                  <el-icon><Delete /></el-icon>
                  清空
                </el-button>
                <el-button type="text" size="small" @click="exportChat">
                  <el-icon><Download /></el-icon>
                  导出
                </el-button>
              </div>
            </div>
            
            <!-- 对话内容 -->
            <div class="chat-messages" ref="messagesContainer">
              <div v-if="currentMessages.length === 0" class="empty-chat">
                <div class="empty-icon">
                  <el-icon><ChatDotRound /></el-icon>
                </div>
                <h3>开始您的AI咨询之旅</h3>
                <p>我可以帮助您解答标书相关问题，提供专业建议</p>
                <div class="suggestion-tags">
                  <el-tag
                    v-for="suggestion in suggestions"
                    :key="suggestion"
                    class="suggestion-tag"
                    @click="sendMessage(suggestion)"
                  >
                    {{ suggestion }}
                  </el-tag>
                </div>
              </div>
              
              <div
                v-for="message in currentMessages"
                :key="message.id"
                class="message"
                :class="message.role"
              >
                <div class="message-avatar">
                  <el-avatar :size="32" :icon="message.role === 'user' ? User : Service" />
                </div>
                <div class="message-content">
                  <div class="message-text" v-html="formatMessage(message.content)"></div>
                  <div class="message-time">{{ formatTime(message.time) }}</div>
                </div>
              </div>
              
              <div v-if="isLoading" class="message assistant">
                <div class="message-avatar">
                  <el-avatar :size="32" :icon="Service" />
                </div>
                <div class="message-content">
                  <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 输入区域 -->
            <div class="chat-input">
              <div class="input-container">
                                 <el-input
                   v-model="inputMessage"
                   type="textarea"
                   :rows="3"
                   placeholder="请输入您的问题..."
                   class="message-input"
                   @keydown.enter.ctrl="() => sendMessage()"
                   resize="none"
                 />
                <div class="input-actions">
                  <span class="input-tip">Ctrl + Enter 发送</span>
                                     <el-button
                     type="primary"
                     :disabled="!inputMessage.trim() || isLoading"
                     @click="() => sendMessage()"
                     class="send-btn"
                   >
                    <el-icon><Position /></el-icon>
                    发送
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from 'vue'
import {
  Plus,
  ChatDotRound,
  Delete,
  Download,
  User,
  Service,
  Position
} from '@element-plus/icons-vue'

// 响应式数据
const activeChatId = ref<string | null>(null)
const inputMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement>()

// 聊天历史
const chatHistory = ref([
  {
    id: '1',
    title: '标书格式咨询',
    lastTime: '2024-01-15T10:30:00'
  },
  {
    id: '2',
    title: '技术方案建议',
    lastTime: '2024-01-14T16:45:00'
  },
  {
    id: '3',
    title: '评分标准分析',
    lastTime: '2024-01-13T09:15:00'
  }
])

// 当前对话消息
const currentMessages = ref<any[]>([])

// 建议问题
const suggestions = [
  '如何提高标书中标率？',
  '标书技术方案怎么写？',
  '投标文件需要哪些材料？',
  '如何分析招标文件？'
]

// 计算属性
const currentChat = computed(() => {
  return chatHistory.value.find(chat => chat.id === activeChatId.value)
})

// 方法
const selectChat = (chatId: string) => {
  activeChatId.value = chatId
  // 加载对应聊天记录
  loadChatMessages(chatId)
}

const loadChatMessages = (chatId: string) => {
  // 模拟加载聊天记录
  if (chatId === '1') {
    currentMessages.value = [
      {
        id: '1',
        role: 'user',
        content: '请问标书格式有什么要求？',
        time: '2024-01-15T10:30:00'
      },
      {
        id: '2',
        role: 'assistant',
        content: '标书格式通常包括以下几个部分：\n\n1. **封面**：项目名称、投标单位、日期等\n2. **目录**：清晰的章节结构\n3. **技术方案**：详细的技术实现方案\n4. **商务方案**：价格、服务承诺等\n5. **附件**：相关证明材料\n\n建议按照招标文件的要求进行组织，确保格式规范、内容完整。',
        time: '2024-01-15T10:31:00'
      }
    ]
  } else {
    currentMessages.value = []
  }
}

const sendMessage = async (content?: string) => {
  const message = content || inputMessage.value.trim()
  if (!message) return
  
  // 添加用户消息
  const userMessage = {
    id: Date.now().toString(),
    role: 'user',
    content: message,
    time: new Date().toISOString()
  }
  currentMessages.value.push(userMessage)
  
  // 清空输入框
  if (!content) {
    inputMessage.value = ''
  }
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 模拟AI回复
  isLoading.value = true
  setTimeout(() => {
    const aiMessage = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: generateAIResponse(message),
      time: new Date().toISOString()
    }
    currentMessages.value.push(aiMessage)
    isLoading.value = false
    
    // 再次滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  }, 1500)
}

const generateAIResponse = (question: string): string => {
  // 简单的AI回复逻辑
  const responses = {
    '如何提高标书中标率': '提高标书中标率的关键点：\n\n1. **深入分析招标文件**：仔细研究评分标准和要求\n2. **突出技术优势**：展示独特的技术方案和创新能力\n3. **优化商务方案**：合理定价，提供增值服务\n4. **完善证明材料**：确保资质、业绩等材料齐全\n5. **注重细节**：格式规范，内容完整，避免低级错误',
    '标书技术方案怎么写': '技术方案编写要点：\n\n1. **项目理解**：准确理解项目需求和目标\n2. **技术路线**：明确技术实现路径和方法\n3. **创新点**：突出技术优势和创新特色\n4. **实施计划**：详细的项目实施步骤和时间安排\n5. **质量保证**：明确质量标准和保障措施\n6. **风险控制**：识别风险点并制定应对策略',
    '投标文件需要哪些材料': '投标文件必备材料：\n\n1. **资质证明**：营业执照、资质证书等\n2. **业绩证明**：相关项目合同、验收报告等\n3. **人员配置**：项目团队简历、证书等\n4. **技术方案**：详细的技术实现方案\n5. **商务报价**：分项报价表和总价\n6. **服务承诺**：质量、工期、服务等承诺\n7. **其他要求**：根据招标文件具体要求提供'
  }
  
  for (const [key, value] of Object.entries(responses)) {
    if (question.includes(key)) {
      return value
    }
  }
  
  return '感谢您的提问！我会根据您的问题提供专业的建议和解答。如果您有具体的标书相关问题，请详细描述，我会尽力帮助您。'
}

const formatMessage = (content: string): string => {
  return content.replace(/\n/g, '<br>')
}

const formatTime = (timeString: string): string => {
  const date = new Date(timeString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const clearChat = () => {
  currentMessages.value = []
}

const exportChat = () => {
  // 导出聊天记录
  console.log('导出聊天记录')
}

// 生命周期
onMounted(() => {
  // 默认选择第一个聊天
  if (chatHistory.value.length > 0) {
    selectChat(chatHistory.value[0].id)
  }
})
</script>

<style lang="scss" scoped>
.consultation-page {
  background: var(--ai-bg-primary);
  min-height: 100vh;
  color: var(--ai-text-primary);
  padding: 24px;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
  
  .page-title {
    background: var(--ai-gradient-primary);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 12px;
  }
  
  .page-subtitle {
    color: var(--ai-text-secondary);
    font-size: 16px;
    font-weight: 400;
  }
}

.page-content {
  max-width: 1400px;
  margin: 0 auto;
}

.consultation-layout {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 24px;
  height: calc(100vh - 200px);
}

// 左侧边栏
.consultation-sidebar {
  background: var(--ai-bg-card);
  backdrop-filter: var(--ai-blur-md);
  border-radius: var(--ai-radius-lg);
  border: 1px solid var(--ai-border);
  box-shadow: var(--ai-shadow-lg);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  background: var(--ai-gradient-subtle);
  border-bottom: 1px solid var(--ai-border);
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h3 {
    color: var(--ai-text-primary);
    font-size: 18px;
    font-weight: 600;
    margin: 0;
  }
}

.new-chat-btn {
  background: var(--ai-gradient-primary);
  border: none;
  color: white;
  box-shadow: var(--ai-shadow-sm);
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: var(--ai-shadow-md);
  }
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.chat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: var(--ai-radius-md);
  cursor: pointer;
  transition: var(--ai-transition);
  margin-bottom: 8px;
  
  &:hover {
    background: var(--ai-bg-overlay);
  }
  
  &.active {
    background: var(--ai-bg-overlay);
    border: 1px solid var(--ai-border-accent);
  }
}

.chat-icon {
  width: 32px;
  height: 32px;
  border-radius: var(--ai-radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--ai-gradient-primary);
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.chat-info {
  flex: 1;
  min-width: 0;
  
  .chat-title {
    color: var(--ai-text-primary);
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .chat-time {
    color: var(--ai-text-tertiary);
    font-size: 12px;
  }
}

// 右侧主区域
.consultation-main {
  background: var(--ai-bg-card);
  backdrop-filter: var(--ai-blur-md);
  border-radius: var(--ai-radius-lg);
  border: 1px solid var(--ai-border);
  box-shadow: var(--ai-shadow-lg);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  background: var(--ai-gradient-subtle);
  border-bottom: 1px solid var(--ai-border);
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--ai-text-primary);
  font-size: 18px;
  font-weight: 600;
}

.chat-actions {
  display: flex;
  gap: 8px;
  
  .el-button {
    color: var(--ai-text-tertiary);
    
    &:hover {
      color: var(--ai-primary);
    }
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.empty-chat {
  text-align: center;
  padding: 60px 20px;
  
  .empty-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: var(--ai-gradient-primary);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32px;
    margin: 0 auto 24px;
  }
  
  h3 {
    color: var(--ai-text-primary);
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 12px;
  }
  
  p {
    color: var(--ai-text-secondary);
    font-size: 14px;
    margin-bottom: 24px;
  }
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  
  .suggestion-tag {
    cursor: pointer;
    transition: var(--ai-transition);
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: var(--ai-shadow-sm);
    }
  }
}

.message {
  display: flex;
  gap: 16px;
  
  &.user {
    flex-direction: row-reverse;
    
    .message-content {
      align-items: flex-end;
      
      .message-text {
        background: var(--ai-gradient-primary);
        color: white;
        border-radius: 18px 18px 4px 18px;
      }
    }
  }
  
  &.assistant {
    .message-content {
      align-items: flex-start;
      
      .message-text {
        background: var(--ai-bg-glass);
        color: var(--ai-text-primary);
        border: 1px solid var(--ai-border-light);
        border-radius: 18px 18px 18px 4px;
      }
    }
  }
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-text {
  padding: 12px 16px;
  line-height: 1.6;
  word-wrap: break-word;
}

.message-time {
  color: var(--ai-text-tertiary);
  font-size: 12px;
  margin-top: 4px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background: var(--ai-bg-glass);
  border: 1px solid var(--ai-border-light);
  border-radius: 18px 18px 18px 4px;
  
  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--ai-text-tertiary);
    animation: typing 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input {
  border-top: 1px solid var(--ai-border-light);
  padding: 20px;
  background: var(--ai-bg-glass);
}

.input-container {
  .message-input {
    :deep(.el-textarea__inner) {
      background: var(--ai-bg-card);
      border: 1px solid var(--ai-border);
      border-radius: var(--ai-radius-md);
      color: var(--ai-text-primary);
      resize: none;
      
      &:focus {
        border-color: var(--ai-primary);
        box-shadow: var(--ai-shadow-sm);
      }
      
      &::placeholder {
        color: var(--ai-text-tertiary);
      }
    }
  }
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-tip {
  color: var(--ai-text-tertiary);
  font-size: 12px;
}

.send-btn {
  background: var(--ai-gradient-primary);
  border: none;
  color: white;
  box-shadow: var(--ai-shadow-sm);
  
  &:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: var(--ai-shadow-md);
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .consultation-layout {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .consultation-sidebar {
    order: 2;
    height: auto;
    max-height: 300px;
  }
  
  .consultation-main {
    order: 1;
  }
}

@media (max-width: 768px) {
  .consultation-page {
    padding: 16px;
  }
  
  .page-header {
    margin-bottom: 24px;
    
    .page-title {
      font-size: 24px;
    }
  }
  
  .consultation-layout {
    height: calc(100vh - 150px);
  }
  
  .chat-header {
    padding: 16px;
  }
  
  .chat-messages {
    padding: 16px;
  }
  
  .chat-input {
    padding: 16px;
  }
  
  .message-content {
    max-width: 85%;
  }
}
</style>
